package com.xiaowu.netmusic.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowu.netmusic.common.constant.MessageConstant;
import com.xiaowu.netmusic.common.exception.UserNotLoginException;
import com.xiaowu.netmusic.common.properties.GithubAppProperties;
import com.xiaowu.netmusic.domain.dto.UserCreateDTO;
import com.xiaowu.netmusic.domain.dto.UserLoginDTO;
import com.xiaowu.netmusic.domain.po.LoginUser;
import com.xiaowu.netmusic.domain.po.UserPO;
import com.xiaowu.netmusic.domain.vo.UserLoginVO;
import com.xiaowu.netmusic.domain.vo.UserVO;
import com.xiaowu.netmusic.service.UserService;
import com.xiaowu.netmusic.utils.JwtUtil;
import com.xiaowu.netmusic.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.lang.ref.PhantomReference;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: xiaowu
 * @time: 2025/4/27 20:28
 */

@RestController("UserController")
@RequestMapping("/user")
@AllArgsConstructor
@Tag(name = "用户操作接口" , description = "用户相关操作")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;

    private final AuthenticationManager authenticationManager;

    private  final GithubAppProperties githubAppProperties;

    private final  StringRedisTemplate redisTemplate;

    private final RestTemplate restTemplate;



    @Operation(summary = "用户注册接口")
    @PostMapping("/register")
    public Result<Object> insertUser(@RequestBody UserCreateDTO userCreateDTO) {

        log.info("{}",userCreateDTO);

        int result = userService.insertUser(userCreateDTO);

        if (result != 0) {
            return Result.success(MessageConstant.REGISTER_SUCCESS);
        } else {
            return Result.error(MessageConstant.REGISTER_FAIL);
        }

    }

    @Operation(summary = "用户登录接口")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {

         // 1. 获取验证码（前端传了 captchaCode 和 captcha）

        // String realCaptcha = redisTemplate.opsForValue().get("captcha:" + userLoginDTO.getCaptchaCode());
        // if (realCaptcha == null || !realCaptcha.trim().equalsIgnoreCase(userLoginDTO.getCaptcha().trim())) {
        //     return Result.error("验证码错误或已过期");
        // }
        //
        // //  2. 验证码校验通过后，删除缓存，防止重复使用
        // redisTemplate.delete("captcha:" + userLoginDTO.getCaptchaCode());

        //  3. 身份认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(userLoginDTO.getLoginInput(), userLoginDTO.getPassword())
        );

        if (authentication == null) {
            throw new UserNotLoginException("登录失败");
        }

        //  4. 后续逻辑照常处理
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        UserPO user = loginUser.getUser();

        String token = JwtUtil.generateToken(user.getId(),user.getUsername());
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .avatarUrl(user.getAvatar())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @Operation(summary = "获图形验证码接口")
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletResponse response) throws Exception {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 40);
        String code = lineCaptcha.getCode();
        String captchaCode = UUID.randomUUID().toString();

        redisTemplate.opsForValue().set("captcha:" + captchaCode, code, 3, TimeUnit.MINUTES);

        // 明确设置响应头（两种方式都加上）
        response.setHeader("Captcha-Code", captchaCode);
        response.addHeader("Access-Control-Expose-Headers", "Captcha-Code"); // 关键！

        response.setContentType("image/png");
        lineCaptcha.write(response.getOutputStream());
    }


    @Operation(summary = "用户信息回显")
    @GetMapping("/one")
    public Result<UserVO> getUserInfo(@RequestParam(name = "id") Long id){
           UserVO userVO = userService.getUserById(id);

           return Result.success(userVO);
    }

    @Operation(summary = "用户修改信息")
    @PostMapping("/update")
    public Result<Object> updateUser(@RequestBody UserCreateDTO userDTO) {
        int update = userService.updateUser(userDTO);

        if (update == 0) {
            return Result.error(MessageConstant.UPDATE_FAIL);
        }
        return Result.success(MessageConstant.UPDATE_SUCCESS);
    }




}
